<style lang="less">
@import "./patrolRiverReal.less";
</style>
<template>
  <div id="containerMap">
    <div id="container1"></div>
    <div id="containerTree">
      <Input
              v-model="searchKey"
              suffix="ios-search"
              @on-change="search"
              placeholder="输入部门名搜索"
              clearable
      />
      <Tree
              ref="tree"
              :data="data"
              show-checkbox
              @on-check-change="changeSelect"
              @on-select-change="selectTree"
      ></Tree>
      <Spin size="large" fix v-if="loading"></Spin>
    </div>
    <Spin size="large" fix v-if="spinShow" style="z-index: 999;"></Spin>
    <Modal title="事件查看" v-model="modalVisible" footer-hide :mask-closable='false' :width="500">
      <p style="font-size: 16px">事件描述&nbsp;:&nbsp;{{eveDatas.eventDescribe}}</p>
      <br>
      <p style="font-size: 16px">上报时间&nbsp;:&nbsp;{{eveDatas.createTime}}</p>
      <br>
      <p style="font-size: 16px">上报人&nbsp;:&nbsp;{{eveDatas.createBy}}</p>
      <br>
      <p style="font-size: 16px">上报地点&nbsp;:&nbsp;{{eveDatas.locality}}</p>
      <br>
      <p style="font-size: 16px">联系方式&nbsp;:&nbsp;{{eveDatas.phone}}</p>
    </Modal>
  </div>

</template>


<script>

  var websocket = null;
  window.onunload = function() {
    //关闭连接  
    this.closeWebSocket();  
  }
  import MapLoader from '@/plugins/amap.js';
  import Cookies from "js-cookie";
  import {
    searchDepartment,
    allDepartment
  } from "@/api/index";
  import {
      getCloseimg,
      getPathArray,
      getSharpimg,
      getXhrimg
  } from '@/plugins/mapPoint.js';
export default {
  name: "patrolRiverReal",
  data() {
    let userInfo = JSON.parse(Cookies.get("userInfo"));
    return {
      userInfo:userInfo,
      modalVisible:false,
      loading:true,
      map:null,
      spinShow:true,
      peopleData:[],
      data: [],
      eventData: [],
      eveDatas: {},
      searchKey:"",
      ids:[],
      time:"",
    };
  },
  methods: {
    //初始化
    init() {
      //初始化webSoket
      this.connectWebSocket();
      let that = this;
      this.getNowTime();
      that.getParentList();
      MapLoader().then(AMap => {
        that.map =new AMap.Map("container1", {
          zoom:11.45,
          zooms:[11,15],
          center:[116.70,40.16],
          pitch: 0,
          viewMode: '3D',
          resizeEnable: true,
          /*layers: [
            // 卫星
            new AMap.TileLayer.Satellite(),
            // 路网
            new AMap.TileLayer.RoadNet()
          ],*/
        });
        that.getRiverPeople();
      that.addPolygon();
        that.spinShow = false;
      }, e => {
        console.log('地图加载失败' ,e)
      })
    },

    //建立WebSocket连接
    connectWebSocket(){
      let wsk = this;

      //建立webSocket连接
      websocket = new WebSocket("ws://localhost:8888/myHandler/ID=" + this.userInfo.id);
      
      //打开webSokcet连接时，回调该函数
      websocket.onopen = function () {   
        console.log("onpen"); 
      }
      
      //关闭webSocket连接时，回调该函数
      websocket.onclose = function () {
        //关闭连接  
        console.log("onclose");
      }
      
      //接收信息
      websocket.onmessage = function (msg) {
        wsk.getRiverPeople();
        // console.log(msg.data);
      }
    },
     
    //关闭连接
    closeWebSocket(){
      if(websocket != null) {
        websocket.close();
      }
    },
 
    getNowTime(){
      var date = new Date();
      this.time = date.toLocaleDateString();
    },

    getRiverPeople(){
      this.loading = true;
      let url = "";
      let param = {};

      param.time = this.time;
      if(this.ids.length > 0){
        url = "/river/getRiverPeoples";
        let idss = this.ids;
        let ids = "";
        for(let i = 0;i<idss.length;i++){
          ids += idss[i]+",";
        }
        ids = ids.substring(0, ids.length - 1);
        param.ids = ids;
      }else{
        url = "/river/getRiverPeople";
      }

      this.postRequest(url,param).then(res => {
        this.loading = false;
        if (res.success) {
          this.peopleData = res.result;
          this.mapClearMarker();
          this.addMarkers();
        }
      });
    },

    getParentList() {
      let that =  this;
      this.loading = true;
      allDepartment().then(res => {
        this.loading = false;
        if (res.success) {
          this.data = this.fn(res.result,"0");
        }
      });
    },
    fn(data, pid) {
      let that = this;
    var result = [], temp;
    for (var i = 0; i < data.length; i++) {
      if (data[i].parentId == pid) {
        var obj = {"title": data[i].title,"id": data[i].id};
        if("0" == pid){
          obj.expand = true;
        }
        temp = that.fn(data, data[i].id);
        if (temp.length > 0) {
          obj.children = temp;
        }
        result.push(obj);
      }
    }
    return result;
  },

    changeSelect(v) {
      let that = this;
      let selected = this.$refs.tree.getSelectedNodes();
      if(selected.length > 0){
        for(let i = 0;i < selected.length;i++){
          selected[i].selected = false;
        }
      }
      let checkIds = [];
      that.ids = checkIds;
      if(v.length > 0){
        for(let i = 0;i <v.length;i++){
          checkIds.push(v[i].id);
        }
        that.ids = checkIds;
      }

      that.getRiverPeople();

    },

    selectTree(v) {
      let that = this;
      let checked = this.$refs.tree.getCheckedAndIndeterminateNodes();
      if(checked.length > 0){
        for(let i = 0;i < checked.length;i++){
          checked[i].checked = false;
          checked[i].indeterminate = false;
        }
      }
      let checkIds = [];
      that.ids = checkIds;
      if(v.length > 0){
        for(let i = 0;i <v.length;i++){
          checkIds.push(v[i].id);
        }
        that.ids = checkIds;
      }
      that.getRiverPeople();
    },

    search() {
      if (this.searchKey) {
        this.loading = true;
        searchDepartment({ title: this.searchKey }).then(res => {
          this.loading = false;
          if (res.success) {
            this.data = res.result;
          }
        });
      } else {
        this.getParentList();
      }
    },
    //画地图点(按群组画)
    addMarkers:function(){
      let eveData = [];
      let that = this;
      window.abClick=function(data){
        let eveData = that.eventData;
        for (let i = 0;i<eveData.length;i++){
            if(data == eveData[i].id){
              that.eveDatas = eveData[i];
              that.modalVisible=true;
            }
        }
      }
      let lnglats = that.peopleData;
      var markers = [];
      let xhrImg = getXhrimg();
      //巡河人图标
      var xhrIcon = new AMap.Icon({
        size: new AMap.Size(50, 50),
        image: xhrImg,
        imageSize: new AMap.Size(48, 48),
      });
      for (var i = 0; i < lnglats.length; i++) {
        var lnglat = lnglats[i];
        if(null != lnglat.user){
          let u = lnglat.user;
          let e = lnglat.eventReport;
          let eve = "<br/>&nbsp;&nbsp;&nbsp;&nbsp;暂无上报";
          if(e.length>0){
            eve = "";
            for(let i = 0;i <e.length;i++){
              eveData.push(e[i]);
              if(e[i].eventDescribe.length>10){
                eve +="<br/><a>"+e[i].eventDescribe.substring(0,10)+"...</a>"
              }else{
                eve +="<br/><a href='#' onclick='abClick("+e[i].id+")'>"+e[i].eventDescribe+"</a>"
              }
            }
          }

          let title = u.username+"---"+u.departmentTitle;
          let content = [];
          /*content.push("<img src='http://tpc.googlesyndication.com/simgad/5843493769827749134'>地址：北京市朝阳区阜通东大街6号院3号楼东北8.3公里");
          content.push("电话：010-64733333");
          content.push("<a href='https://ditu.amap.com/detail/B000A8URXB?citycode=110105'>详细信息</a>");*/
          content.push("河流名称:"+lnglat.riverName +
                  "<br/>"+
                  "巡河开始时间:"+lnglat.patrolStartTime +
                  "<br/>"+
                  "起始坐标:<br/>"+
                  "&nbsp;&nbsp;&nbsp;&nbsp;经度:"+lnglat.longitude+
                  "<br/>"+
                  "&nbsp;&nbsp;&nbsp;&nbsp;纬度:"+lnglat.dimensionality+
                  "<br/>"+
                  "巡河上报事件:"+
                  eve
          );
          // content.push("<br/>");
          // content.push("<a href="+lnglat.address+" target='_blank'>详细信息</a>");
          // 创建点实例
          let marker = new AMap.Marker({
            title:title,
            animation:"AMAP_ANIMATION_DROP",
            position: new AMap.LngLat(lnglat.longitude, lnglat.dimensionality),
            icon: xhrImg,
            extData: {
              id: lnglat.id
            }
          });
          marker.content = this.createInfoWindow(title,content);
          marker.on('click', that.markerClick);
          // marker.emit('click', {target: marker});
          markers.push(marker);
        }
      }
      this.map.add(new AMap.OverlayGroup(markers));
      this.eventData = eveData;
      // this.map.clearInfoWindow();
    },
    //标点点击事件
    markerClick:function(e) {
      var infoWindow = new AMap.InfoWindow({isCustom:true,closeWhenClickMap:true,offset: new AMap.Pixel(30, -40)});
      infoWindow.setContent(e.target.content);
      infoWindow.open(this.map, e.target.getPosition());
  },

  //构建自定义信息窗体
  createInfoWindow:function(title, content) {
    let that = this;
    var info = document.createElement("div");
    info.className = "custom-info input-card content-window-card";


    //可以通过下面的方式修改自定义窗体的宽高
    info.style.width = "300px";
    // 定义顶部标题
    var top = document.createElement("div");
    var titleD = document.createElement("div");
    var closeX = document.createElement("img");
    top.className = "info-top";
    titleD.innerHTML = title;
    titleD.onclick = that.map.clearInfoWindow( );
    closeX.src = getCloseimg();
    closeX.onclick = that.mapClearInfoWindow;

    top.appendChild(titleD);
    top.appendChild(closeX);
    info.appendChild(top);

    // 定义中部内容
    var middle = document.createElement("div");
    middle.className = "info-middle";
    middle.style.backgroundColor = 'white';
    middle.innerHTML = content;
    info.appendChild(middle);

    // 定义底部内容
    var bottom = document.createElement("div");
    bottom.className = "info-bottom";
    bottom.style.position = 'relative';
    bottom.style.top = '0px';
    bottom.style.margin = '0 auto';
    var sharp = document.createElement("img");
    sharp.src = getSharpimg();
    bottom.appendChild(sharp);
    info.appendChild(bottom);
    return info;
  },

    //关闭地图弹窗
    mapClearInfoWindow:function(){
      this.map.clearInfoWindow();
    },

    //清除地图所有点
    mapClearMarker:function(){
      let markers = this.map.getAllOverlays('marker')
      this.map.remove(markers);
    },

    //画地图遮罩
      addPolygon:function(){
          let that = this;
          /* new AMap.DistrictSearch({
             extensions:'all',
             subdistrict:0
           }).search('顺义区',function(status,result) {*/
          // 外多边形坐标数组和内多边形坐标数组
          // var outer = [
          //   new AMap.LngLat(-180,90,true),
          //   new AMap.LngLat(-180,-90,true),
          //   new AMap.LngLat(180,-90,true),
          //   new AMap.LngLat(180,90,true),
          // ];
          // var holes = result.districtList[0].boundaries
          // var pathArray = [
          //     outer
          // ];
          //顺义区地图遮罩边界
          var holes = getPathArray();
         var polygon = new AMap.Polygon( {
              path:holes,
              strokeColor: 'rgb(0,0,0)',
              strokeWeight: 3,
              strokeOpacity:1,
              fillColor: 'rgba(255,255,255)',
              fillOpacity: 0,
              strokeStyle:'dashed',
              strokeDasharray:[10,2]
          });
          // polygon.setPath(holes);
          that.map.add(polygon);
          // })
      },

  },
  mounted(){
    this.init();
  },

  created() {
  }
};
</script>

